package router

import (
	"jgt-oper/src/logger"
	"jgt-oper/src/util"
	"jgt-sdk/asapi"

	"github.com/facebookgo/inject"
	"github.com/spf13/viper"
	"github.com/teambition/gear"
)

// SrvRouterV1Handler 初始化srv/v1路由
func SrvRouterV1Handler(g *inject.Graph) *gear.Router {
	router := gear.NewRouter(gear.RouterOptions{
		Root:                  "/srv/v1",
		IgnoreCase:            true,
		FixedPathRedirect:     true,
		TrailingSlashRedirect: true,
	})

	runMode := viper.GetString("run_mode")
	if runMode == util.ProdMode {
		// 验证令牌
		router.Use(func(ctx *gear.Context) error {
			var traceID string
			if v, err := ctx.Any(util.GetTraceIDKey()); err == nil && v != nil {
				traceID = v.(string)
			}

			token := ctx.GetHeader(util.TokenKey)
			logger.System(traceID).Infof("访问令牌：%s", token)
			_, err := asapi.GetAPIWithTraceID(traceID).VerifyToken(token)
			if err != nil {
				logger.System(traceID).Infof("验证请求令牌发生错误：%v", err)
				return gear.ErrUnauthorized.WithMsg("无效的授权")
			}
			return nil
		})
	} else {
		router.Use(DefaultUserMiddleware)
	}

	// 增加检查用户中间件
	router.Use(CheckUserMiddleware())

	// 注册路由映射
	SrvDemoMap(g, router)
	SrvUserMap(g, router)
	SrvEnterpriseMap(g, router)
	SrvDictionaryMap(g, router)
	SrvParkMap(g, router)
	SrvSystemParameterMap(g, router)

	return router
}
